package com.micromall.common.utils;

import org.apache.commons.lang.StringUtils;

/**
 * create by DanteFung on 2017-6-21 11:06:52
 */
public class WhereClauseBudiler {

        private String baseSQL = "";
        private String targetSQL = "";

        private void init(String fields, String tableName){
            if (StringUtils.isNotBlank(fields)
                    && ( fields.startsWith(",") || (!fields.startsWith(",") && !fields.contains(",")) )
                    ) {
                throw new RuntimeException("ERROR:fields的格式有误！正确的格式为 例如： t.username,t.password ");
            }
            StringBuffer sb = new StringBuffer();
            this.baseSQL = sb.append(" SELECT ")
                             .append(StringUtils.isNotBlank(fields)?fields:"*")
                             .append(" FROM ")
                             .append(tableName)
                             .append(" WHERE 1=1").toString();
        }

        public WhereClauseBudiler(){

        }

        public WhereClauseBudiler initBaseSQL(String fields,String tableName){
            init(fields, tableName);
            return this;
        }

        public WhereClauseBudiler(String fields, String tableName){
            init(fields, tableName);
        }

        public WhereClauseBudiler addCondition(String condition){
            if(StringUtils.isBlank(baseSQL)){
                throw new RuntimeException("EORROR:baseSQL未被初始化！SUGGESTION:请通过构造方法或initBaseSQL方法初始化!");
            }

            if(StringUtils.isNotBlank(condition)){
                if(StringUtils.isBlank(targetSQL)){
                    targetSQL = baseSQL + " AND " + condition;
                }else {
                    targetSQL += " AND " + condition;
                }
            }
            return this;
        }

        public String build() {
            return StringUtils.isNotBlank(targetSQL)?targetSQL:baseSQL;
        }
}